package fm.controller;

import com.mongodb.DBObject;
import fm.dto.NeiyiUser;
import fm.exception.BizException;
import fm.mongoService.UserService;
import fm.util.CommonUtils;
import fm.yichenet.mongo.service.ArticleService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资讯页面
 * Created by Javon on 2018/1/12.
 */
@Controller
@RequestMapping("/info")
public class InfoController extends BaseController {
    @Autowired
    ArticleService articleService;
    @Autowired
    UserService userService;

    @RequestMapping("")
    public String index(ModelMap modelMap) {

        return "portal/info";
    }

    @ResponseBody
    @RequestMapping("/info/list")
    public Map getAllInfo(@RequestParam(defaultValue = "1", required = true) Integer pageNum,
                          @RequestParam(defaultValue = "10", required = true) Integer pageSize) {
        Map res = new HashMap();
        try {
            Map param = new HashMap();
            List<DBObject> infoList = articleService.getArticleForPage(param, pageSize, pageNum);
            long count = articleService.countArticles(param);
            if (CollectionUtils.isNotEmpty(infoList)) {
                for (DBObject info : infoList) {
                    if(info.get("user_id").equals("0")){
                        info.put("userContact","联系本站客服");
                    }
                    else {
                        NeiyiUser user = userService.getById((String) info.get("user_id"));
                        if (CommonUtils.isEmpty(user)) {
                            throw new BizException("用戶未找到!");
                        }
                        info.put("userContact", user.getUserContact());
                    }
                }
            }
            res.put("data", infoList);
            res.put("total",count);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }



}
